package com.stone.serverless.web;

import cn.hutool.core.util.ObjectUtil;
import com.stone.serverless.sdk.utils.JsonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.nio.charset.StandardCharsets;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/25 19:04
 * @Version: 1.0.0
 */
public class RpcServiceHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        Annotation[] parameterAnnotations = returnType.getParameterAnnotations();
        return parameterAnnotations.length == 0;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        if(ObjectUtil.isNotNull(returnValue)){
            HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
            response.getOutputStream().write(JsonUtil.toStr(returnValue).getBytes(StandardCharsets.UTF_8));
        }
    }
}
